<template>
	<view class="date-time-container" :class="containerClass">
		<!-- 取还车信息区域 -->
		<!-- 		<view class="pickup-return-info">
			<view class="pickup-info">
				<text class="title">取车</text>
				<text class="date">{{ formatPickupDate || '-' }}</text>
				<text class="week-time">{{ formatPickupDateTime || '-' }}</text>
			</view>

			<view class="duration">
				<text>{{ formatDuration }}</text>
			</view>

			<view class="return-info">
				<text class="title">还车</text>
				<text class="date">{{ formatReturnDate || '-' }}</text>
				<text class="week-time">{{ formatReturnDateTime || '-' }}</text>
			</view>
		</view> -->
		<view>
			<view>

			</view>
			<view>


				<view style="margin: auto;width: 90%;display: flex;justify-content: space-between;">
				<!-- 	<uni-data-checkbox mode="tag" max="1" multiple v-model="value" :localdata="huodong"
						@change="change"></uni-data-checkbox> -->
						<view @click="change(item,index)" v-for="(item,index) in huodong" :class="{ 'item': true, 'active': activeIndex === index }" style="border-radius: 8px;border: 1px solid #ddd;padding: 10px 30px;">
							{{item.text}}
						</view>
				</view>



			</view>
		</view>
		<!-- 日历区域 -->
		<view class="calendar-section">
			<view class="calendar-header">
				<text class="month-switcher" @click="changeMonth(-12)">《</text>
				<text class="month-switcher" @click="changeMonth(-1)">〈</text>
				<text class="current-month">{{formatYearMonth}}</text>
				<text class="month-switcher" @click="changeMonth(1)">〉</text>
				<text class="month-switcher" @click="changeMonth(12)">》</text>
			</view>

			<view class="weekday-header">
				<text v-for="day in ['日','一','二','三','四','五','六']" :key="day">{{ day }}</text>
			</view>

			<!-- 这里后续需要通过js动态生成日历格子 -->
			<view class="calendar-grid">
				<view v-for="(day, index) in calendarDaysMemo" :key="index" class="calendar-day" :class="{
							'disabled': day.disabled,
							'selected': day.selected,
							'start-date': day.isStartDate,
							'end-date': day.isEndDate,
							'in-range': day.inRange,
							'today': day.isToday,
							'empty': !day.date
						}" @click="selectDate(day, index)">
					<view class="day-content">
						<view class="date-content">
							<text>{{ day.date }}</text>
							<!-- <text>{{ 库存占位 }}</text> -->
							<text v-if="day.isStartDate && !day.isEndDate" class="date-tag">开始</text>
							<text v-else-if="day.isEndDate && !day.isStartDate" class="date-tag">结束</text>
							<text v-else-if="day.isStartDate && day.isEndDate" class="date-tag">开始/结束</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 时间选择区域 -->
		<view class="time-picker-section">
			<view class="time-columns">
				<!-- 取车时间选择器 -->
				<!-- #ifdef MP-WEIXIN || MP-ALIPAY || H5 -->
				<view class="time-column">
					<text class="time-title">取货时间</text>
					<picker-view class="time-picker" :value="pickupTimeIndex" @change="onPickupTimeChange">
						<picker-view-column>
							<view class="time-item" v-for="time in availablePickupTimes" :key="time">{{time}}</view>
						</picker-view-column>
					</picker-view>
				</view>
				<!-- #endif -->

				<!-- #ifdef APP-PLUS -->
				<view class="time-column">
					<text class="time-title">取货时间</text>
					<picker class="time-picker" mode="time" :value="pickupTime" :start="minTime" :end="maxTime"
						@change="onPickupTimeChange">
						<view class="picker-value">{{pickupTime}}</view>
					</picker>
				</view>
				<!-- #endif -->

				<!-- 还车时间选择器 -->
				<!-- #ifdef MP-WEIXIN || MP-ALIPAY || H5 -->
				<view class="time-column">
					<text class="time-title">归还时间</text>
					<picker-view class="time-picker" :value="returnTimeIndex" @change="onReturnTimeChange">
						<picker-view-column>
							<view class="time-item" v-for="time in availableReturnTimes" :key="time">{{time}}</view>
						</picker-view-column>
					</picker-view>
				</view>
				<!-- #endif -->

				<!-- #ifdef APP-PLUS -->
				<view class="time-column">
					<text class="time-title">归还时间</text>
					<picker class="time-picker" mode="time" :value="returnTime" :start="minTime" :end="maxTime"
						@change="onReturnTimeChange">
						<view class="picker-value">{{returnTime}}</view>
					</picker>
				</view>
				<!-- #endif -->
			</view>
		</view>

		<!-- 底部按钮区域 -->
		<view class="bottom-buttons">
			<button class="reset-btn" @click="handleReset">重置</button>
			<button class="confirm-btn" @click="handleConfirm">确定</button>
		</view>
	</view>
</template>

<script>
	const CONFIG = {
		MAX_RENTAL_DAYS: 30,
		MIN_RENTAL_HOURS: 1,
		DEFAULT_PICKUP_TIME: '09:00',
		DEFAULT_RETURN_TIME: '09:00',
		TIME_STEP: 30
	}

	export default {
		name: 'DateTimeRangePicker',
		props: {
			// 初始开始日期时间
			startDateTime: {
				type: [String, Date],
				default: null
			},
			// 初始结束日期时间
			endDateTime: {
				type: [String, Date],
				default: null
			},
			// 最小可选日期
			minDate: {
				type: [String, Date],
				default: () => {
					const date = new Date()
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
				}
			},
			// 最大可选日期
			maxDate: {
				type: [String, Date],
				default: () => {
					const date = new Date()
					date.setFullYear(date.getFullYear() + 1)
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
				}
			},
			// 时间间隔（分钟）
			timeStep: {
				type: Number,
				default: 30
			},
			// 是否显示顶部信息栏
			showHeader: {
				type: Boolean,
				default: true
			},
			defaultStartDate: {
				type: String,
				default: ''
			},
			defaultStartTime: {
				type: String,
				default: ''
			},
			defaultEndDate: {
				type: String,
				default: ''
			},
			defaultEndTime: {
				type: String,
				default: ''
			}
		},

		emits: ['update:startDateTime', 'update:endDateTime', 'confirm', 'reset'],

		data() { 
			return {
				
      activeIndex: null,
				pickupTime: this.defaultStartTime || '09:00',
				returnTime: this.defaultEndTime || '09:00',
				pickupTimeIndex: [0],
				returnTimeIndex: [0],
				currentMonth: '2024-12',
				calendarDays: [],
				huodong: [{
						text: '自提',
						value: '1'
					},
					{
						text: '闪送',
						value: '2'
					},
					{
						text: '顺丰快递',
						value: '3'
					}
				],
				timeList: [],
				cid: '',
				startDate: this.defaultStartDate ? new Date(this.defaultStartDate) : null,
				endDate: this.defaultEndDate ? new Date(this.defaultEndDate) : null,
				platform: '',
				isIOS: false,
				minTime: '00:00',
				value: '',
				maxTime: '23:59',
				timeListCache: null,
				calendarDaysCache: {}
			}
		},

		created() {
			// 获取平台信息
			// #ifdef APP-PLUS
			this.platform = 'app'
			this.isIOS = uni.getSystemInfoSync().platform === 'ios'
			// #endif

			// #ifdef H5
			this.platform = 'h5'
			// #endif

			// #ifdef MP
			this.platform = 'mp'
			// #endif

			// 创建防抖版本的 changeMonth
			this.debouncedChangeMonth = this.debounce((offset) => {
				const [year, month] = this.currentMonth.split('-').map(Number)
				const date = new Date(year, month - 1 + offset, 1)
				const newYear = date.getFullYear()
				const newMonth = date.getMonth() + 1

				this.currentMonth = `${newYear}-${String(newMonth).padStart(2, '0')}`
				this.generateCalendarDays()
			})

			// 初始化数据
			this.initializeComponent()

			// 确保日历状态正确更新
			this.$nextTick(() => {
				this.updateCalendarDays()
			})

			// 添加日志检查主题色
			console.log('Theme color in created:', this.themeColor)
		},

		mounted() {
			// 添加日志检查主题色
			console.log('Theme color in mounted:', this.themeColor)
			this.initializeComponent()
		},

		computed: {
			formatYearMonth() {
				const [year, month] = this.currentMonth.split('-')
				return `${year}年${month}月`
			},

			// 修改取 时间的计算属性
			availablePickupTimes() {
				// 如果没有选择开始日期，显示所有时间
				if (!this.startDate) {
					return this.timeList
				}

				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

				// 只有当选择的是今天时，才需要过滤掉已经过去的时间
				if (this.startDate.toDateString() === today.toDateString()) {
					const currentHour = now.getHours()
					const currentMinute = now.getMinutes()

					return this.timeList.filter(time => {
						const [hour, minute] = time.split(':').map(Number)
						if (hour < currentHour) return false
						if (hour === currentHour && minute <= currentMinute + 30) return false
						return true
					})
				}

				// 如果不是今天，显示所有时间
				return this.timeList
			},

			// 修改还车时间的计算属性
			availableReturnTimes() {
				// 如果没有选择开始日期，显示所有时间
				if (!this.startDate) {
					return this.timeList
				}

				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

				// 如果结束日期是今天，过滤掉已经过去的时间
				if (this.endDate?.toDateString() === today.toDateString()) {
					const currentHour = now.getHours()
					const currentMinute = now.getMinutes()
					const [pickupHour, pickupMinute] = this.pickupTime.split(':').map(Number)

					return this.timeList.filter(time => {
						const [hour, minute] = time.split(':').map(Number)
						// 先检查是否超过当前时间
						if (hour < currentHour) return false
						if (hour === currentHour && minute <= currentMinute + 30) return false
						// 如果开始日期也是今天，还要检查是否在取车时间之后
						if (this.startDate.toDateString() === today.toDateString()) {
							if (hour < pickupHour || (hour === pickupHour && minute <= pickupMinute)) return false
						}
						return true
					})
				}

				// 如果是同一天，确保还车时间至少比取车时间晚1小时
				if (this.startDate?.toDateString() === this.endDate?.toDateString()) {
					const [pickupHour, pickupMinute] = this.pickupTime.split(':').map(Number)
					return this.timeList.filter(time => {
						const [hour, minute] = time.split(':').map(Number)
						const timeDiff = (hour * 60 + minute) - (pickupHour * 60 + pickupMinute)
						return timeDiff >= 60 // 至少1小时
					})
				}

				// 如果结束日期不是今天，显示所有时间
				return this.timeList
			},

			// 格式化取车日期
			formatPickupDate() {
				if (!this.startDate) return '年-月-日'
				return `${this.startDate.getFullYear()}-${String(this.startDate.getMonth() + 1).padStart(2, '0')}-${String(this.startDate.getDate()).padStart(2, '0')}`
			},

			// 格式化取车时间和星期
			formatPickupDateTime() {
				if (!this.startDate) return '--:--'
				const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][this.startDate.getDay()]
				return `${weekDay} ${this.pickupTime}`
			},

			// 格式化还车日期
			formatReturnDate() {
				if (!this.endDate) return '年-月-日'
				return `${this.endDate.getFullYear()}-${String(this.endDate.getMonth() + 1).padStart(2, '0')}-${String(this.endDate.getDate()).padStart(2, '0')}`
			},

			// 格式化还车时间和星期
			formatReturnDateTime() {
				if (!this.endDate) return '--:--'
				const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][this.endDate.getDay()]
				return `${weekDay} ${this.returnTime}`
			},

			// 格式化时长显示
			formatDuration() {
				if (!this.startDate || !this.endDate || !this.pickupTime || !this.returnTime) return '-小时'

				try {
					// 创建新的日期对象，避免修改原始日期
					const start = new Date(this.startDate)
					const end = new Date(this.endDate)

					// 设置时间
					const [startHour, startMinute] = this.pickupTime.split(':').map(Number)
					const [endHour, endMinute] = this.returnTime.split(':').map(Number)

					start.setHours(startHour, startMinute, 0, 0)
					end.setHours(endHour, endMinute, 0, 0)

					// 计算时间差（毫秒）
					const diff = end.getTime() - start.getTime()

					// 计算总小时数（向上取整）
					const totalHours = Math.ceil(diff / (60 * 60 * 1000))

					// 计算天数和小时数
					const days = Math.floor(totalHours / 24)
					const hours = totalHours % 24

					// 格式化显示
					if (days === 0) {
						return `${totalHours}小时`
					} else if (hours === 0) {
						return `${days}天`
					} else {
						return `${days}天${hours}小时`
					}
				} catch (error) {
					console.error('计算时长出错:', error)
					return '-小时'
				}
			},

			timeListMemo() {
				if (this.timeListCache) {
					return this.timeListCache
				}

				const times = []
				for (let hour = 0; hour < 24; hour++) {
					for (let minute = 0; minute < 60; minute += this.timeStep) {
						times.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`)
					}
				}
				this.timeListCache = times
				return times
			},

			calendarDaysMemo() {
				const cacheKey = `${this.currentMonth}_${this.startDate?.getTime()}_${this.endDate?.getTime()}`
				if (this.calendarDaysCache[cacheKey]) {
					return this.calendarDaysCache[cacheKey]
				}

				const days = this.generateCalendarDays()
				this.calendarDaysCache[cacheKey] = days
				this.calendarDays = days
				return days
			},

			containerClass() {
				// #ifdef H5
				return 'h5-container'
				// #endif

				// #ifdef MP
				return 'mp-container'
				// #endif

				// #ifdef APP-PLUS
				return 'app-container'
				// #endif

				return ''
			}
		},

		methods: {
			change(e,index) {
				console.log(e)
				 this.activeIndex = index;
				this.cid = e.value
			},
			debounce(fn, delay = 300) {
				let timer = null
				return (...args) => {
					if (timer) clearTimeout(timer)
					timer = setTimeout(() => {
						fn.apply(this, args)
					}, delay)
				}
			},

			onPickupTimeChange(e) {
				// #ifdef APP-PLUS
				if (e.detail && e.detail.value) {
					this.pickupTime = e.detail.value
				}
				// #endif

				// #ifdef MP || H5
				const index = e.detail.value[0]
				const newTime = this.availablePickupTimes[index]
				if (newTime) {
					this.pickupTime = newTime
					this.pickupTimeIndex = [this.availablePickupTimes.indexOf(newTime)]
				}
				// #endif
			},
			onReturnTimeChange(e) {
				// #ifdef APP-PLUS
				if (e.detail && e.detail.value) {
					this.returnTime = e.detail.value
				}
				// #endif

				// #ifdef MP || H5
				const index = e.detail.value[0]
				const newTime = this.availableReturnTimes[index]
				if (newTime) {
					this.returnTime = newTime
					this.returnTimeIndex = [this.availableReturnTimes.indexOf(newTime)]
				}
				// #endif
			},
			generateCalendarDays() {
				try {
					const [year, month] = this.currentMonth.split('-').map(Number)
					const firstDay = new Date(year, month - 1, 1)
					const lastDay = new Date(year, month, 0)
					const today = new Date()
					today.setHours(0, 0, 0, 0)

					const maxDate = this.parseDate(this.maxDate)
					const minDate = this.parseDate(this.minDate)

					if (!maxDate || !minDate) {
						throw new Error('Invalid date range')
					}

					const days = []
					const firstDayWeek = firstDay.getDay()
					const daysInMonth = lastDay.getDate()

					// 填充月初空白日期
					for (let i = 0; i < firstDayWeek; i++) {
						days.push({
							date: '',
							disabled: true
						})
					}

					// 生成当月日期
					for (let i = 1; i <= daysInMonth; i++) {
						const currentDate = new Date(year, month - 1, i)
						currentDate.setHours(0, 0, 0, 0)

						const isStartDate = this.startDate && this.isSameDay(currentDate, this.startDate)
						const isEndDate = this.endDate && this.isSameDay(currentDate, this.endDate)
						const inRange = this.isDateInRange(currentDate)

						days.push({
							date: i,
							disabled: currentDate < minDate || currentDate > maxDate,
							selected: isStartDate || isEndDate,
							isToday: this.isSameDay(currentDate, today),
							isStartDate: isStartDate,
							isEndDate: isEndDate,
							inRange: inRange
						})
					}

					// 填充月末空白
					const totalDays = firstDayWeek + daysInMonth
					const remainingDays = Math.ceil(totalDays / 7) * 7 - totalDays
					for (let i = 0; i < remainingDays; i++) {
						days.push({
							date: '',
							disabled: true
						})
					}

					return days
				} catch (error) {
					console.error('Calendar generation error:', error)
					return []
				}
			},
			parseDate(date) {
				if (!date) return null

				try {
					const parsedDate = typeof date === 'string' ? new Date(date) : date
					parsedDate.setHours(0, 0, 0, 0)
					return this.isValidDate(parsedDate) ? parsedDate : null
				} catch {
					return null
				}
			},
			isDateInRange(date) {
				if (!this.startDate || !this.endDate) return false
				const startTime = this.startDate.getTime()
				const endTime = this.endDate.getTime()
				const currentTime = date.getTime()
				return currentTime > startTime && currentTime < endTime
			},
			updateAvailableTimes() {
				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

				if (this.startDate?.toDateString() === today.toDateString()) {
					const availableTimes = this.availablePickupTimes
					if (availableTimes.length > 0) {
						this.pickupTime = availableTimes[0]
						this.pickupTimeIndex = [0]
					}
				}

				if (this.endDate) {
					const availableTimes = this.availableReturnTimes
					if (availableTimes.length > 0) {
						this.returnTime = availableTimes[0]
						this.returnTimeIndex = [0]
					}
				}
			},
			selectPickupTime(time) {
				this.pickupTime = time
			},
			selectReturnTime(time) {
				this.returnTime = time
			},

			selectDate(day, index) {
				if (day.disabled || !day.date) return

				if (!this.startDate || (this.startDate && this.endDate)) {
					// 开始新的选择
					this.startDate = this.getDateFromDay(day)
					this.endDate = null

					const now = new Date()
					const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

					if (this.startDate.toDateString() === today.toDateString()) {
						// 如果选择今天，使用 updateAvailableTimes 来设置最早可用时间
						this.updateAvailableTimes()
					} else {
						// 如果选择其他日期，保持当前选中的时间
						const currentPickupTime = this.availablePickupTimes[this.pickupTimeIndex[0]]
						if (currentPickupTime) {
							this.pickupTime = currentPickupTime
						}
					}
				} else {
					// 选择结束日期
					const endDate = this.getDateFromDay(day)
					const now = new Date()
					const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

					if (endDate < this.startDate) {
						this.startDate = endDate
						this.endDate = null
						if (endDate.toDateString() === today.toDateString()) {
							this.updateAvailableTimes()
						} else {
							// 保持当前选中的时间
							const currentPickupTime = this.availablePickupTimes[this.pickupTimeIndex[0]]
							if (currentPickupTime) {
								this.pickupTime = currentPickupTime
							}
						}
					} else {
						this.endDate = endDate
						// 如果结束日期和开始日期是同一天，还车时间应该在取车时间之后
						if (this.endDate.toDateString() === this.startDate.toDateString()) {
							const [pickupHour, pickupMinute] = this.pickupTime.split(':').map(Number)
							const availableReturnTimes = this.timeList.filter(time => {
								const [hour, minute] = time.split(':').map(Number)
								const timeDiff = (hour * 60 + minute) - (pickupHour * 60 + pickupMinute)
								return timeDiff >= 60 // 至少1小时
							})

							// 检查是否有可用的还车时间
							if (availableReturnTimes.length === 0) {
								// 如果没有可用的还车时间，重置结束日期并提示用户
								this.endDate = null
								uni.showToast({
									title: '当天无法完成最少1小时的租期，请选择其他日期',
									icon: 'none',
									duration: 2000
								})
								this.updateCalendarDays()
								return
							}

							// 设置第一个可用的还车时间
							this.returnTime = availableReturnTimes[0]
							this.returnTimeIndex = [this.timeList.indexOf(this.returnTime)]
						} else {
							// 保持当前选中的时间
							const currentReturnTime = this.availableReturnTimes[this.returnTimeIndex[0]]
							if (currentReturnTime) {
								this.returnTime = currentReturnTime
							}
						}
					}
				}
				this.updateCalendarDays()

				// 添加最大租期限制（例如30天）
				const MAX_RENTAL_DAYS = 30
				if (this.startDate && !this.endDate) {
					const selectedDate = this.getDateFromDay(day)
					const diffTime = Math.abs(selectedDate - this.startDate)
					const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

					if (diffDays > MAX_RENTAL_DAYS) {
						uni.showToast({
							title: `租期不能超过${MAX_RENTAL_DAYS}天`,
							icon: 'none'
						})
						return
					}
				}
			},
			getDateFromDay(day) {
				const [year, month] = this.currentMonth.split('-').map(Number)
				return new Date(year, month - 1, day.date)
			},
			updateCalendarDays() {
				this.generateCalendarDays()
			},
			changeMonth(offset) {
				const [year, month] = this.currentMonth.split('-').map(Number)
				const date = new Date(year, month - 1 + offset, 1)
				const newYear = date.getFullYear()
				const newMonth = date.getMonth() + 1

				this.currentMonth = `${newYear}-${String(newMonth).padStart(2, '0')}`
				// 清除当前月份的缓存
				const cacheKey = `${this.currentMonth}_${this.startDate?.getTime()}_${this.endDate?.getTime()}`
				delete this.calendarDaysCache[cacheKey]
				// 强制更新日历
				this.$nextTick(() => {
					this.calendarDays = this.calendarDaysMemo
				})
			},

			// 确认选择
			handleConfirm() {
				if (!this.startDate || !this.endDate) {
					uni.showToast({
						title: '请选择完整的租赁时间',
						icon: 'none'
					})
					return
				}
				if (this.cid == '') {
					uni.showToast({
						title: '请选择配送方式',
						icon: 'none'
					})
					return
				}

				// 检查时间是否合理
				const startDateTime = this.parseDateTime(this.formatDateTime(this.startDate, this.pickupTime))
				const endDateTime = this.parseDateTime(this.formatDateTime(this.endDate, this.returnTime))
				const now = new Date()
				console.log(123)
				if (!startDateTime || !endDateTime) {
					uni.showToast({
						title: '日期格式错误',
						icon: 'none'
					})
					return
				}

				if (startDateTime < now) {
					uni.showToast({
						title: '取回时间不能早于当前时间',
						icon: 'none'
					})
					return
				}

				const diffHours = (endDateTime - startDateTime) / (1000 * 60 * 60)
				console.log(111)
				if (diffHours < 1) {
					uni.showToast({
						title: '租赁时长不能少于1小时',
						icon: 'none'
					})
					return
				}

				// 获取周几
				const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
				const startWeekDay = weekDays[this.startDate.getDay()]
				const endWeekDay = weekDays[this.endDate.getDay()]
	
				// 构建返回数据
				const result = {
					start: {
						date: this.formatDate(this.startDate),
						weekDay: startWeekDay,
						time: this.pickupTime,
						fullDateTime: this.formatDateTime(this.startDate, this.pickupTime)
					},
					end: {
						date: this.formatDate(this.endDate),
						weekDay: endWeekDay,
						time: this.returnTime,
						fullDateTime: this.formatDateTime(this.endDate, this.returnTime)
					},
					duration: this.calculateDuration(startDateTime, endDateTime),
					 pickupType: this.cid
				}
console.log(222)
				// 触发确认事件
				this.$emit('confirm', result)
			},

			// 重置选择
			handleReset() {
				// 重置日期选择
				this.startDate = null
				this.endDate = null
				this.cid = ''
				// 重置时间选择
				this.pickupTime = '09:00'
				this.returnTime = '09:00'
				this.pickupTimeIndex = [0]
				this.returnTimeIndex = [0]

				// 重置日历显示
				this.updateCalendarDays()

				// 重置月份为当前月份
				const now = new Date()
				this.currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`

				// 触发重置事件
				this.$emit('update:startDateTime', null)
				this.$emit('update:endDateTime', null)
				this.$emit('reset')

				// 提示用户重置成功
				uni.showToast({
					title: '已重置',
					icon: 'none'
				})
			},

			// 格式化日期时间
			formatDateTime(date, time) {
				try {
					const year = date.getFullYear()
					const month = String(date.getMonth() + 1).padStart(2, '0')
					const day = String(date.getDate()).padStart(2, '0')

					// iOS日期格式特殊处理
					if (this.isIOS) {
						return `${year}/${month}/${day} ${time}:00`
					}
					return `${year}-${month}-${day}T${time}:00`
				} catch (error) {
					console.error('日期格式化错误:', error)
					return ''
				}
			},

			// 添加一个安全的日期解析方法
			parseDateTime(dateTimeStr) {
				try {
					// 处理包含空格的日期时间字符串
					if (dateTimeStr.includes(' ')) {
						dateTimeStr = dateTimeStr.replace(' ', 'T')
					}
					const date = new Date(dateTimeStr)
					return this.isValidDate(date) ? date : null
				} catch (error) {
					console.error('日期解析错误:', error)
					return null
				}
			},

			// 计算时间间隔
			calculateDuration(startDateTime, endDateTime) {
				const start = new Date(startDateTime)
				const end = new Date(endDateTime)
				const diff = end - start

				const days = Math.floor(diff / (24 * 60 * 60 * 1000))
				const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))

				return {
					days,
					hours,
					totalHours: days * 24 + hours
				}
			},

			// 添加日期验证
			isValidDate(date) {
				return date instanceof Date && !isNaN(date)
			},

			isSameDay(date1, date2) {
				if (!date1 || !date2) return false
				return date1.getFullYear() === date2.getFullYear() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getDate() === date2.getDate()
			},

			formatDate(date) {
				if (!date) return ''
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			// 优化时间验证逻辑
			validateTimeRange(startDateTime, endDateTime) {
				const now = new Date()
				const diffHours = (endDateTime - startDateTime) / (1000 * 60 * 60)

				if (startDateTime < now) {
					this.showToast('取回时间不能早于当前时间')
					return false
				}

				if (diffHours < CONFIG.MIN_RENTAL_HOURS) {
					this.showToast(`租赁时长不能少于${CONFIG.MIN_RENTAL_HOURS}小时`)
					return false
				}

				return true
			},

			// 统一提示方法
			showToast(title, icon = 'none') {
				uni.showToast({
					title,
					icon
				})
			},

			// 添加错误边界处理
			handleError(error, fallback) {
				console.error(error)
				return fallback
			},

			// 优化日期处理方法
			parseDateSafely(dateString) {
				try {
					const date = new Date(dateString)
					return this.isValidDate(date) ? date : null
				} catch (error) {
					return this.handleError(error, null)
				}
			},

			initializeComponent() {
				const now = new Date()
				this.currentMonth = this.formatDate(now).slice(0, 7)

				// 如果有默认值，设置日期和时间
				if (this.defaultStartDate) {
					this.startDate = new Date(this.defaultStartDate)
					this.pickupTime = this.defaultStartTime || '09:00'
					// 设置时间选择器的索引
					this.pickupTimeIndex = [this.timeList.indexOf(this.pickupTime)]
				}

				if (this.defaultEndDate) {
					this.endDate = new Date(this.defaultEndDate)
					this.returnTime = this.defaultEndTime || '09:00'
					// 设置时间选择器的索引
					this.returnTimeIndex = [this.timeList.indexOf(this.returnTime)]
				}

				// 初始化日历
				this.calendarDays = this.calendarDaysMemo
				// 初始化时间列表
				this.timeList = this.timeListMemo
			},

			// 优化事件处理方法
			handleDateSelect(day) {
				if (this.isDateDisabled(day)) return

				if (!this.startDate || (this.startDate && this.endDate)) {
					this.handleStartDateSelect(day)
				} else {
					this.handleEndDateSelect(day)
				}

				this.updateCalendarDays()
			},

			isDateDisabled(day) {
				return day.disabled || !day.date
			},

			formatTime(date) {
				if (!date) return '09:00'
				return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},

			// 优化时间选择处理
			handleTimeChange(type, value) {
				try {
					const timeValue = this.validateTimeValue(value)
					if (!timeValue) return

					if (type === 'pickup') {
						this.pickupTime = timeValue
						// 如果是同一天,确保还车时间合法
						if (this.startDate?.toDateString() === this.endDate?.toDateString()) {
							this.validateReturnTime()
						}
					} else {
						this.returnTime = timeValue
					}
				} catch (error) {
					console.error('Time change error:', error)
				}
			},

			// 验证时间值
			validateTimeValue(time) {
				if (!time) return null

				const [hours, minutes] = time.split(':').map(Number)
				if (isNaN(hours) || isNaN(minutes)) return null
				if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null

				return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
			},

			// 验证还车时间
			validateReturnTime() {
				if (!this.pickupTime || !this.returnTime) return

				const [pickupHour, pickupMinute] = this.pickupTime.split(':').map(Number)
				const [returnHour, returnMinute] = this.returnTime.split(':').map(Number)

				const pickupMinutes = pickupHour * 60 + pickupMinute
				const returnMinutes = returnHour * 60 + returnMinute

				if (returnMinutes <= pickupMinutes + 60) {
					// 自动调整还车时间为取车时间后一小时
					const newReturnMinutes = pickupMinutes + 60
					const newHour = Math.floor(newReturnMinutes / 60)
					const newMinute = newReturnMinutes % 60

					this.returnTime = `${newHour.toString().padStart(2, '0')}:${newMinute.toString().padStart(2, '0')}`
				}
			},

			// 清理缓存
			clearCache() {
				this.timeListCache = null
				this.calendarDaysCache = {}
			}
		},

		// 添加生命周期钩子
		beforeDestroy() {
			// 清理缓存和定时器
			this.clearCache()
			if (this.debounceTimer) {
				clearTimeout(this.debounceTimer)
			}
		},

		// 优化监听器
		watch: {
			timeStep() {
				// 时间步长改变时清除时间列表缓存
				this.timeListCache = null
			},

			currentMonth() {
				// 月份改变时清除对应的日历缓存
				this.calendarDaysCache = {}
			},

			// 添加对日历数据的监听
			calendarDaysMemo: {
				handler(newDays) {
					this.calendarDays = newDays
				},
				immediate: true
			},

			// 添加对默认值的监听
			defaultStartDate(newVal) {
				if (newVal) {
					this.startDate = new Date(newVal)
					this.updateCalendarDays()
				}
			},
			defaultStartTime(newVal) {
				if (newVal) {
					this.pickupTime = newVal
					this.pickupTimeIndex = [this.timeList.indexOf(newVal)]
				}
			},
			defaultEndDate(newVal) {
				if (newVal) {
					this.endDate = new Date(newVal)
					this.updateCalendarDays()
				}
			},
			defaultEndTime(newVal) {
				if (newVal) {
					this.returnTime = newVal
					this.returnTimeIndex = [this.timeList.indexOf(newVal)]
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 定义变量
	$border-radius: 8rpx;
	$transition-duration: 0.3s;
	$shadow-color: rgba(0, 0, 0, 0.05);

	.date-time-container {
		box-sizing: border-box;
		padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));

		.pickup-return-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			padding-top: calc(30rpx + constant(safe-area-inset-top));
			padding-top: calc(30rpx + env(safe-area-inset-top));
			background-color: #ffffff;
			margin-bottom: 20rpx;

			.pickup-info,
			.return-info {
				display: flex;
				flex-direction: column;
				flex: 1;
				max-width: 40%;

				.title {
					font-size: 26rpx;
					color: #666;
					margin-bottom: 12rpx;
				}

				.date,
				.week-time {
					min-height: 1em;
				}
			}

			.pickup-info {
				text-align: left;

				.date,
				.week-time {
					text-align: left;
				}
			}

			.return-info {
				text-align: right;

				.date,
				.week-time {
					text-align: right;
				}
			}

			.duration {
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: #666;
				flex: 0 0 auto;
				min-width: 120rpx;
				text-align: center;
				background-color: #fff;
				padding: 10rpx 20rpx;
				border-radius: 30rpx;
				box-shadow: 0 2rpx 8rpx $shadow-color;
			}
		}

		.calendar-section {
			padding: 20rpx;
			background-color: #f8f8f8;
			width: 100%;
			box-sizing: border-box;

			.calendar-header {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 20rpx;

				.month-switcher {
					padding: 0 20rpx;
					color: #666;
					cursor: pointer;

					&:active {
						opacity: 0.7;
					}
				}

				.current-month {
					font-size: 32rpx;
					font-weight: bold;
					padding: 0 40rpx;
				}
			}

			.weekday-header {
				display: grid;
				grid-template-columns: repeat(7, 1fr);
				width: 100%;
				padding: 20rpx 0;
				box-sizing: border-box;

				text {
					text-align: center;
					font-size: 28rpx;
					color: #666;
				}
			}

			.calendar-grid {
				display: grid;
				grid-template-columns: repeat(7, 1fr);
				gap: 0;
				padding: 20rpx 0;
				box-sizing: border-box;
				width: 100%;

				.calendar-day {
					position: relative;
					width: 100%;
					height: 0;
					padding-bottom: 100%;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;

					&.empty {
						background: none;
					}

					&.disabled {
						color: #ccc;
					}

					&.today {
						.day-content {
							color: #8BC34A;
							font-weight: bold;
						}
					}

					&.start-date {
						.day-content {
							background-color: #8BC34A;
							color: #fff;
							border-radius: $border-radius 0 0 $border-radius;
							margin-right: -1px;
						}

						&.end-date {
							.day-content {
								border-radius: $border-radius;
							}
						}
					}

					&.end-date {
						.day-content {
							background-color: #8BC34A !important;
							color: #fff !important;
							border-radius: 0 $border-radius $border-radius 0;
							margin-left: -1px;
						}
					}

					&.start-date.end-date {
						.day-content {
							margin: 0;
							border-radius: $border-radius;
						}
					}

					&.in-range {
						.day-content {
							background-color: rgba(139, 195, 74, 0.1);
							color: #8BC34A;
						}
					}

					// 添加一个内部容器来放置内容
					.day-content {
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						display: flex;
						justify-content: center;
						align-items: center;
						transition: all $transition-duration ease;
					}

					.date-content {
						width: 100%;
						height: 100%;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;

						text {
							line-height: 1.2;

							&:first-child {
								margin-bottom: 4rpx;
							}

							&.date-tag {
								font-size: 20rpx;
								color: inherit;
								white-space: nowrap;
							}
						}
					}
				}
			}
		}

		.time-picker-section {
			padding: 20rpx 30rpx;

			.time-columns {
				display: flex;
				justify-content: space-between;

				.time-column {
					flex: 1;

					.time-title {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 20rpx;
						display: block;
						text-align: center;
					}

					.time-picker {
						height: 200rpx;

						.time-item {
							height: 80rpx;
							line-height: 80rpx;
							font-size: 28rpx;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}

		.bottom-buttons {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 100;
			display: flex;
			padding: 20rpx 30rpx;
			background-color: #fff;
			box-shadow: 0 -2rpx 10rpx $shadow-color;
			width: 100%;
			box-sizing: border-box;

			/* 统一处理安全区域 */
			/* #ifdef MP */
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
			/* #endif */

			/* #ifndef MP */
			padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
			/* #endif */

			button {
				flex: 1;
				margin: 0 10rpx;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				border-radius: $border-radius;
				transition: opacity 0.2s ease;

				&:active {
					opacity: 0.8;
				}

				@media screen and (max-height: 667px) {
					height: 70rpx;
					line-height: 70rpx;
					font-size: 26rpx;
				}
			}

			.reset-btn {
				background-color: #fff;
				border: 2rpx solid #ddd;
				color: #333;
			}

			.confirm-btn {
				background-color: #8BC34A;
				color: #fff;
			}
		}
	}

	@media screen and (max-width: 375px) {
		.date-time-container {
			.pickup-return-info {
				padding: 20rpx;
				padding-top: calc(20rpx + constant(safe-area-inset-top));
				padding-top: calc(20rpx + env(safe-area-inset-top));

				.pickup-info,
				.return-info {
					.title {
						font-size: 24rpx;
					}

					.date {
						font-size: 30rpx;
					}

					.week-time {
						font-size: 22rpx;
					}
				}

				.duration {
					font-size: 22rpx;
					min-width: 100rpx;
					padding: 8rpx 16rpx;
				}
			}

			.calendar-section {
				.calendar-day {
					font-size: 26rpx;
				}
			}
		}
	}

	/* H5端特殊样式 */
	// #ifdef H5
	.h5-container {
		.time-picker-section {
			.time-picker {
				/* H5特有的样式 */
			}
		}
	}

	// #endif

	/* 小程序端特殊样式 */
	// #ifdef MP
	.mp-container {
		.time-picker-section {
			.time-picker {
				/* 小程序特有的样式 */
			}
		}
	}

	// #endif

	/* App端特殊样式 */
	// #ifdef APP-PLUS
	.app-container {
		.time-picker-section {
			.picker-value {
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				font-size: 28rpx;
				background-color: #f8f8f8;
				border-radius: 8rpx;
			}
		}
	}

	// #endif
</style>
<style scoped lang="scss">
	.item {
	  background-color: #ddd;
	}
	
	.item.active {
	  background-color: #8bc34a;
	  color: #fff;
	}
	::v-deep .uni-data-checklist .checklist-group {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	::v-deep .uni-data-checklist .checklist-group .checklist-box.is--tag {
		margin-right: 10px;
		padding: 10px 30px;
		border: 1px #DCDFE6 solid;
		border-radius: 3px;
		background-color: #f5f5f5;
	}
	
</style>